﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YXShop.IDAL;
using System.Data;
using System.Text.RegularExpressions;
namespace YXShop.TemplateAction
{
    public class FreeLabel:Template
    {
        /// <summary>
        /// 自由标签参数
        /// </summary>
        struct StParam
        {
            /// <summary>
            /// 参数名称
            /// </summary>
            public string name;
            /// <summary>
            /// 所在SQL语句的位置
            /// </summary>
            public int pos;
        }
        /// <summary>
        /// 标签内容
        /// </summary>
        private string LabelContent = string.Empty;
        /// <summary>
        /// 自由标签的SQL语句
        /// </summary>
        private string LabelSQL = string.Empty;
        public string LabelSqlFree
        {
            get { return LabelSQL; }
            set { LabelSQL = value; }
        }
        /// <summary>
        /// 自由标签样式()
        /// </summary>
        private string LabelStyle = string.Empty;

        public string LabelStyleFree
        {
            get { return LabelStyle; }
            set { LabelStyle = value; }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="labelname">自由标签名称</param>
        public FreeLabel(string labelname, string labeltype)
            : base(labelname, labeltype)
        { }
        /// <summary>
        /// 从数据库取得自由标签内容
        /// </summary>
        /// <param name="cn">已打开的数据库连接</param>
        public override void GetContentFromDB()
        {
            YXShop.BLL.Templates.FreeLabel lbll = new YXShop.BLL.Templates.FreeLabel();
            List<YXShop.Model.Templates.FreeLabel> data = lbll.GetListByWhere(" free_name = '" + _LabelName+ "'");
            if (data.Count > 0)
            {
                LabelContent = data[0].StyleContent;
                LabelSQL = data[0].LabelSql;
                LabelStyle = data[0].StyleContent;

            }
        }
        public static YXShop.IDAL.Templates.IFreeLabel IL = YXShop.DALFactory.DataAccess.CreateFreeLabel();
        /// <summary>
        /// 生成最终的HTML代码
        /// </summary>
        /// <param name="cn"></param>
        /// 

        public override void MakeHtmlCode()
        {
            if (LabelStyle == string.Empty)
            {
                this._FinalHtmlCode = string.Empty;
                return;
            }

            string FinalStr = this.LabelStyle;
            #region 时间处理
            string pattertm = @"\[\$[^\$]+\$\]";
            Regex regex = new Regex(pattertm, RegexOptions.Compiled);

            Match match = regex.Match(FinalStr);
            DateTime Now = DateTime.Now;
            while (match.Success)
            {
                string tm;
                string _tm = tm = match.Value;
                _tm = Regex.Replace(_tm, @"^\[\$|\$\]$", "");
                _tm = _tm.Replace("YY02", Now.Year.ToString().Remove(0, 2));
                _tm = _tm.Replace("YY04", Now.Year.ToString());
                _tm = _tm.Replace("MM", Now.Month.ToString());
                _tm = _tm.Replace("DD", Now.Day.ToString());
                _tm = _tm.Replace("HH", Now.Hour.ToString());
                _tm = _tm.Replace("MI", Now.Minute.ToString());
                _tm = _tm.Replace("SS", Now.Second.ToString());
                FinalStr = FinalStr.Replace(tm, _tm);
                match = regex.Match(FinalStr);
            }
            //替换
            //[$YY02年MM月DD日$]日期格式
            #endregion
            IList<StParam> FieldsList = ParseFields(FinalStr);
            DataTable dt = ChangeHope.DataBase.DataHelper.GetDataTableBySql(LabelSQL);//IL.ExcuteTable(LabelSQL);
            int d = dt.Rows.Count;//SQL记录条数
            //记录不循环记录的编号
            List<int> UnLoopNum = new List<int>();
            #region 先找不循环
            string pattern = @"\{\*(?<n>\d+)(?<c>[\S\s]*?)\*\}";
            Regex reg = new Regex(pattern, RegexOptions.Compiled);
            Match m = reg.Match(FinalStr);
            while (m.Success)
            {
                string rcd = m.Value;
                string newrcd = m.Groups["c"].Value.Trim();
                int rcdindex = Convert.ToInt32(m.Groups["n"].Value);
                UnLoopNum.Add(rcdindex - 1);
                if (FieldsList != null)
                {
                    for (int i = 0; i < FieldsList.Count; i++)
                    {
                        string FieldName = FieldsList[i].name;
                        string FieldValue = string.Empty;
                        if (dt != null && dt.Rows.Count >= rcdindex && dt.Rows[rcdindex - 1][FieldsList[i].pos] != DBNull.Value)
                        {
                            FieldValue = dt.Rows[rcdindex - 1][FieldsList[i].pos].ToString();
                        }
                        newrcd = ReplaceField(newrcd, FieldName, FieldValue);
                    }
                }
                FinalStr = FinalStr.Replace(rcd, newrcd);
                m = m.NextMatch();

            }
            #endregion 先找不循环
            #region 处理循环
            pattern = @"\{\#[\s\S]*?\#\}";
            Regex r = new Regex(pattern, RegexOptions.Compiled);
            m = r.Match(FinalStr);
            while (m.Success)
            {
                string mstr = m.Value;
                string _mstr = mstr.Substring(2, mstr.Length - 4);
                string reslt = string.Empty;
                string row = string.Empty;
                string col = string.Empty;
                string pat = @"\[YX:unLoop,[^\]]+\][\s\S]*?\[/YX:unLoop\]|\[YX:Loop,[^\]]+\][\s\S]*?\[/YX:Loop\]";
                Regex regTg = new Regex(pat, RegexOptions.Compiled);
                //FinalStr = FinalStr.Replace(mstr, reslt);
                // Match mlq = regTg.Match(FinalStr);
                m = regTg.Match(FinalStr);
                string showMode = string.Empty;
                //在模版中显示 预览的时候没添加到数据库不用显示
                if (m.Success)
                {   //显示几行几列
                    string ms = m.Value.Trim();
                    LabelParse lp = new LabelParse(ms);
                    lp.ParseContent();
                    row = lp.GetParamValue("YX:ShowRows");  //显示行
                    col = lp.GetParamValue("YX:ShowCols");  //显示列
                    showMode = lp.GetParamValue("YX:ShowMode");//显示方式
                }
                if (row != null && !row.Equals(""))
                {
                    StringBuilder valstr = new StringBuilder();
                    //table 显示循环
                    if (showMode == "2")
                    {
                        int countitem = 0;
                        for (int i = 0; i < d; i++)
                        {
                            countitem++;  
                            if(countitem>int.Parse(row)*int.Parse(col))
                            {
                                break;
                            }
                            //设置的行数>=每页记录数 超出索引 就返回有的                
                            if (UnLoopNum.Contains(i))
                                continue;
                            UnLoopNum.Add(i);                                                  
                            string varName = _mstr;     
                                if (FieldsList != null)
                                {
                                    for (int j = 0; j < FieldsList.Count; j++)
                                    {
                                        string FieldName = FieldsList[j].name;
                                        string FieldValue = string.Empty;
                                        if (dt.Rows[i][FieldsList[j].pos] != DBNull.Value)
                                        {
                                            FieldValue = dt.Rows[i][FieldsList[j].pos].ToString();
                                        }
                                        varName = ReplaceField(varName, FieldName, FieldValue);                                                                                          
                                    }
                                    //循环TD
                                    valstr.Append("<td>");
                                    valstr.Append(varName);
                                    valstr.Append("</td>");
                                 }
                                if ((countitem % Convert.ToInt32(col)) == 0)
                                {
                                    //换行
                                    valstr.Append("</tr><tr>");
                                }
                        }
                        reslt = valstr.ToString();
                    }
                    else
                    {
                        //div显示循环
                        for (int i = 0; i < d; i++)
                        {
                            if (i > int.Parse(row) * int.Parse(col))
                                break;
                            if (UnLoopNum.Contains(i))
                                continue;
                            UnLoopNum.Add(i);
                            string strvar = _mstr;                    
                            if (FieldsList != null)
                                {
                                    for (int j = 0; j < FieldsList.Count; j++)
                                    {
                                        string FieldName = FieldsList[j].name;
                                        string FieldValue = string.Empty;
                                        if (dt.Rows[i][FieldsList[j].pos] != DBNull.Value)
                                        {
                                            FieldValue = dt.Rows[i][FieldsList[j].pos].ToString();
                                        }
                                        strvar = ReplaceField(strvar, FieldName, FieldValue);
                                    }
                                }
                           reslt += strvar;                        
                        }
                    }
                }
                FinalStr = FinalStr.Replace(mstr, reslt);
                m = m.NextMatch();
            }
            #endregion 处理循环
            string patternBody = @"\[YX:unLoop,[^\]]+\][\s\S]*?\[/YX:unLoop\]|\[YX:Loop,[^\]]+\][\s\S]*?\[/YX:Loop\]";
            Regex regT = new Regex(patternBody, RegexOptions.Compiled);
            Match ml = regT.Match(FinalStr);
            while (ml.Success)
            {
                string ms = ml.Value.Trim();
                LabelParse labelparse = new LabelParse(ms);
                labelparse.ParseContent();
                string s = labelparse.Parse();
                FinalStr = FinalStr.Replace(ms, s);
                ml = regT.Match(FinalStr);
            }
            FieldsList.Clear();
            dt.Clear();
            dt.Dispose();
            this._FinalHtmlCode = FinalStr;
            if (d > 0)
            {
                this._FinalDateTable = dt;
            }
        }
        /// <summary>
        /// 解析SQL语句的字段位置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        private IList<StParam> ParseFields(string Input)
        {
            string SqlFields = Regex.Match(LabelSQL, @"^select\ +(top\ +\d+\ +)?(?<flds>.+)\ +from\ +.+", RegexOptions.Compiled | RegexOptions.IgnoreCase).Groups["flds"].Value.Trim();
            if (SqlFields.Equals(string.Empty))
            {
                return null;
            }
            string[] Fields = null;
            if (SqlFields.IndexOf(",") > 0)
                Fields = SqlFields.Trim().Split(',');
            else
                Fields = new string[] { SqlFields };
            string pattern = @"\[\*(?<fld>[\s\S]+?)\*\]";
            IList<StParam> pms = new List<StParam>();
            Regex reg = new Regex(pattern, RegexOptions.Compiled);
            Match m = reg.Match(Input);
            while (m.Success)
            {
                StParam p;
                p.name = m.Groups["fld"].Value;
                p.pos = -1;
                bool flag = false;
                foreach (StParam sp in pms)
                {
                    if (sp.name.Equals(p.name))
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    for (int i = 0; i < Fields.Length; i++)
                    {
                        if (Fields[i].Trim().Equals(p.name.Trim()))
                        {
                            p.pos = i;
                            pms.Add(p);
                            break;
                        }
                    }
                }
                m = m.NextMatch();
            }
            return pms;
        }
        protected string ReplaceField(string Input, string FieldName, string FieldValue)
        {
            if (Input == null || Input.Trim() == string.Empty)
                return string.Empty;
            string RetVal = Input;
            string pattern = @"\(\#[Ll][Ee][Ff][Tt]\(\[\*" + Regex.Escape(FieldName) + @"\*\]\,(?<n>\d+)\)\#\)";
            Regex r = new Regex(pattern, RegexOptions.Compiled);
            Match mymatch = r.Match(Input);
            if (mymatch.Success)
            {
                int pos = int.Parse(mymatch.Groups["n"].Value);
                FieldValue = ChangeHope.Common.StringHelper.SubString(FieldValue, pos);
                RetVal = Regex.Replace(Input, pattern, FieldValue);
            }
            else
            {
                string tabStr = testTable(FieldName);

                RetVal = Input.Replace("[*" + FieldName + "*]", FieldValue);


            }
            return RetVal;
        }

        protected string testTable(string FieldName)
        {
            string returnStr = "";
            string fld = FieldName;
            string[] arr = null;
            if (FieldName.IndexOf('.') != -1)
            {
                arr = FieldName.Split('.');
                returnStr = arr[0];
                fld = arr[1];
            }
            else
            {

            }
            returnStr = returnStr.ToLower();
            fld = fld.ToLower();
            return returnStr;
        }

    }
}
